﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using Htse.Blue.Models;
using System.Linq.Dynamic;

namespace Htse.Blue.Logic
{
	public class AccountMembershipService : IMembershipService
	{
		private MembershipProvider _membershipProvider;
		private RoleProvider _roleProvider;

		public AccountMembershipService()
			: this(null, null)
		{
		}

		public AccountMembershipService(MembershipProvider membershipProvider, RoleProvider roleProvider)
		{
			_membershipProvider = membershipProvider ?? Membership.Provider;

			_roleProvider = roleProvider ?? (Roles.Enabled ? Roles.Provider : null);
		}

		public int MinPasswordLength
		{
			get
			{
				return _membershipProvider.MinRequiredPasswordLength;
			}
		}

		public bool ValidateUser(string userName, string password)
		{
			return _membershipProvider.ValidateUser(userName, password);
		}

		public MembershipCreateStatus CreateUser(string userName, string password, string email)
		{
			MembershipCreateStatus status;
			_membershipProvider.CreateUser(userName, password, email, null, null, true, null, out status);
			return status;
		}

		public bool ChangePassword(string userName, string oldPassword, string newPassword)
		{
			MembershipUser currentUser = _membershipProvider.GetUser(userName, true /* userIsOnline */);
			return currentUser.ChangePassword(oldPassword, newPassword);
		}

		public PagedList<MembershipUser> ListUsers(int? page, int pageSize, string sortingParameter)
		{
			int dummy = 0;
			var users = _membershipProvider.GetAllUsers(0, Int32.MaxValue, out dummy);

			List<MembershipUser> usersList = new List<MembershipUser>();

			foreach (MembershipUser user in users)
			{
				usersList.Add(user);
			}

			if (string.IsNullOrEmpty(sortingParameter))
			{
				return usersList.AsQueryable().ToPagedList(page, pageSize);
			}
			else
			{
				return usersList.AsQueryable().OrderBy(sortingParameter).ToPagedList(page, pageSize, sortingParameter);
			}
		}

		public IQueryable<string> ListAllUserNames()
		{
			int totalRecords;

			var users = _membershipProvider.GetAllUsers(0, 1000, out totalRecords);

			IList<string> userNames = new List<string>();

			foreach (MembershipUser user in users)
			{
				userNames.Add(user.UserName);
			}

			return userNames.AsQueryable();
		}

		public bool DeleteUser(string userName)
		{
			return _membershipProvider.DeleteUser(userName, true);
		}

		public IQueryable<string> GetAllRoles()
		{
			return _roleProvider.GetAllRoles().AsQueryable();
		}

		public void AddUserToRole(string userName, string roleName)
		{
			_roleProvider.AddUsersToRoles(new string[] { userName }, new string[] { roleName });
		}
	}
}
